package com.neulogistics.contrib.transfercenter.api.controller;


import com.neulogistics.contrib.transfercenter.domain.exception.TransferCenterDomainException;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ErrorCode;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器
 *
 * @author WLX
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//    @ExceptionHandler(CustomerDomainException.class)
//    public BaseResponse<?> CustomerDomainExceptionHandler(CustomerDomainException e) {
//        log.error("CustomerDomainException: " + e.getMessage(), e);
//        return ResultUtils.error(e.getCode(), e.getMessage());
//    }

    @ExceptionHandler(TransferCenterDomainException.class)
    public BaseResponse<?> OrderDomainExceptionHandler(TransferCenterDomainException e) {
        log.error("{}: " + e.getMessage(), TransferCenterDomainException.class.getSimpleName(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public BaseResponse<?> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        log.error(msg, e);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse<?> ConstraintViolationExceptionHandler(ConstraintViolationException  e) {
        log.error("ConstraintViolationException", e);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR);
    }


}
